/****************************************************************************
 * 2025.4 APU
 ****************************************************************************/

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using QFramework;
using System.Linq;
using QAssetBundle;

namespace QFramework.Example
{
	public partial class CoinShopPanel : UIElement, IController
	{
		Dictionary<string, CoinUpgradeItem> dic_dic_CoinUpgradeItems;

		List<CoinUpgradeItem> list_CoinUpgradeItems;
		private void Awake()
		{
			CoinUpgradeSystem.OnCoinUpgradeSystemChanged.Register(() =>
			{
				OnRefresh();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);


			OnRefresh();
			OnClickCoinShopPanel();
		}

		protected override void OnBeforeDestroy()
		{
		}

		private void OnRefresh()
		{
			

			DicRefresh();
			//ListRefresh();

		}

		private void ListRefresh()
		{
			CoinUpgradeBtnParent.DestroyChildren();
			list_CoinUpgradeItems = this.GetSystem<CoinUpgradeSystem>().list_CoinUpgradeItems;
			foreach (var item in list_CoinUpgradeItems.Where(item =>item.ConditionCheck()))
			{
				CoinUpgradeItem.InstantiateWithParent(CoinUpgradeBtnParent)
				.Self(self =>
				{
					var coinItem = item;
					var varSelf = self;
					varSelf.GetComponentInChildren<Text>().text = item.Description;
					varSelf.onClick.AddListener(() =>
					{
						AudioKit.PlaySound(Sfx.LEVELUP);
						coinItem.Upgrade(coinItem);
						varSelf.GetComponentInChildren<Text>().text = item.Description;
					});
				})
				.Show();
			}
		}

		private void DicRefresh()
		{
			dic_dic_CoinUpgradeItems = this.GetSystem<CoinUpgradeSystem>().dic_CoinUpgradeItems;
			foreach (var item in dic_dic_CoinUpgradeItems.Values)
			{
				CoinUpgradeItem.InstantiateWithParent(CoinUpgradeBtnParent)
				.Self(self =>
				{
					var coinItem = item;
					var varSelf = self;
					varSelf.GetComponentInChildren<Text>().text = item.Description;
					varSelf.onClick.AddListener(() =>
					{
						AudioKit.PlaySound(Sfx.LEVELUP);
						coinItem.Upgrade(coinItem);
						varSelf.GetComponentInChildren<Text>().text = item.Description;
					});
				})
				.Show();
			}
		}

		/// <summary>
		/// 购买界面
		/// </summary>
		private void OnClickCoinShopPanel()
		{

			CloseBtn.onClick.AddListener(() =>
			{
				this.Hide();
			});

			Global.Coin.RegisterWithInitValue(coin =>
			{
				TextCoin.text = "金币：" + coin;
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
		}

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}